/**
 * Copyright (c) 2024 Huawei Technologies Co., Ltd.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE-MIT file in the root directory of this source tree.
 */

import type { TurboModuleContext } from '../../RNOH/TurboModule';
import { TurboModule } from '../../RNOH/TurboModule';
import { RNOHLogger } from '../../RNOH/RNOHLogger';
import { preferences } from '@kit.ArkData';
import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

export class SettingsTurboModule extends TurboModule {
  public static readonly NAME = 'SettingsManager';

  private settingsManagerStoreId = "settings_manager_store"

  private logger: RNOHLogger;

  private dataPreferences:  preferences.Preferences | null = null;

  constructor(protected ctx: TurboModuleContext) {
    super(ctx);
    this.logger = this.ctx.logger.clone('SettingsTurboModule');
    this.createKVManager()
  }
  async createKVManager(){
    try {
      const context: common.UIAbilityContext = this.ctx.uiAbilityContext as common.UIAbilityContext;
      let res = await preferences.getPreferences(context, this.settingsManagerStoreId)
      this.dataPreferences = res;
      this.logger.info("Succeeded in creating store",this.dataPreferences,res)
    } catch (e) {
      let error = e as BusinessError;
      console.error(`Failed to create KVManager.code is ${error.code},message is ${error.message}`);
    }
  }

  get(key:string){
    let value:any = "";
    try{
      let res = this.dataPreferences?.getSync(key, '')
      console.log("zzk get ===>",res)
      value = JSON.stringify(res)
      console.log("zzk get ===> value default", value)
      return value
    }catch (e){
      console.log("zzk get ===> value catch", value)
      return value
    }
  }

  set(key,value){
    console.log("zzk key ==> set",key,value)
    if(!this.dataPreferences) return;
    try{
      this.dataPreferences?.putSync(key, value)
      console.log("zzk key ==> set success")
    } catch (e) {
      console.log("zzk key ==> set error")
    }
    this.dataFlush();
  }

  dataFlush(){
    this.dataPreferences?.flush()
  }

  onWatch(){}

  offWatch(){}


  watchKeys(keys, callback){

  }

  clearWatch(watchId:number){
    // if(!this.kvManager) return;
    console.log("zzk watchId", watchId)
  }
}
